import React, { Component } from 'react'
import styles from "./index.less"
import path from "path"
import PropTypes from 'prop-types';
export default class index extends Component {
  constructor(props) {
    super(props)

    this.state = {
      initMediaWidth: 1,
      initMediaHeight: 1,
      mediaWidth: "100%",
      mediaHeight: "auto",
    }
  }
  loadComplete() {
    //设置媒体的初始高度，变化时作为参考
    this.setState({
      initMediaWidth:this.BgMedia.clientWidth,
      initMediaHeight:this.BgMedia.clientHeight,
    })
    this.setMedia(this.BgMedia.clientWidth, this.BgMedia.clientHeight, document.body.clientWidth, document.body.clientHeight);
    window.addEventListener("resize", () => {
      this.setMedia(this.state.initMediaWidth, this.state.initMediaHeight, document.body.clientWidth, document.body.clientHeight)
    })
  }
  setMedia(width, height, windowWidth, windowHeight) {
    this.setState(height / width >= windowHeight / windowWidth ?
      {
        mediaWidth: "100%",
        mediaHeight: "auto",
      } :
      {
        mediaWidth: "auto",
        mediaHeight: "100%",
      }
    )
  }
  render() {
    return (
      <div ref={(_) => (this.fixBg = _)} id="fixBg" className={styles.fixBg}>
        {path.extname(this.props.src).toLowerCase() == ".mp4" ?
          <video ref={(_) => (this.BgMedia = _)} className={styles.fixBgMedia}
            onCanPlayThrough={() => this.loadComplete()}
            style={{
              width: `${this.state.mediaWidth}`,
              height: `${this.state.mediaHeight}`,
            }}
            src={this.props.src} autoPlay="autoPlay" loop="loop" muted></video>
          :
          <img ref={(_) => (this.BgMedia = _)} className={styles.fixBgMedia}
            onLoad={() => this.loadComplete()}
            style={{
              width: `${this.state.mediaWidth}`,
              height: `${this.state.mediaHeight}`,
            }}
            src={this.props.src} alt="" />
        }
        <div className={styles.fixBgMediaOver} style={this.props.overLayerStyle ? this.props.overLayerStyle : {}}></div>
      </div>
    )
  }
}
index.propTypes = {
  src: PropTypes.string.isRequired,
  overLayerStyle: PropTypes.object,
}